package com.xshbbs.interceptor;

import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xshbbs.entity.User;
import com.xshbbs.service.UserService;

public class LoginInterceptor implements HandlerInterceptor {
	
	@Autowired
	private UserService userService;
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
//		System.out.println("执行方法afterCompletion");
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
//		System.out.println("执行方法postHandle");
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//请求前设置字符编码
		response.setCharacterEncoding("UTF-8");
		
		HttpSession session = request.getSession();
		String uri = request.getRequestURI();
		// 获取请求路径
//        String url = request.getRequestURL().toString();
//		System.out.println(uri);
//		System.out.println(url);
		if (uri.equals("/xshbbs/login") || uri.equals("/xshbbs/register")) {
			return true;
		} else {
			Object obj = session.getAttribute("user");
			if (obj != null) {
				return true;
			} else {
				Cookie[] cookies = request.getCookies();
				if (cookies != null) {
					// 有cookie就通过cookie获取用户信息
					// 遍历cookies
					for (Cookie cookie : cookies) {
						if (cookie.getName().equals("username")) {
							String username = cookie.getValue();
							username = URLDecoder.decode(username, "UTF-8");
							// 当cookie中有username才执行
							// 获取用户数据
							User user = this.userService.selectUserByUsername(username);
							// 登录成功设置session
							session.setAttribute("user", user);
//							request.getRequestDispatcher("/index.jsp").forward(request, response);
							return true;
						}
					}
				}
			}
		}
		if(uri.equals("/xshbbs/forum") || uri.equals("/xshbbs/ps.login")) {
			return true;
		}
		response.sendRedirect("ps.login");
		return false;

	}
	
}
